import { reqGetCode, reqFinishRegister, reqUserLogin, reqUserInfo, reqLoginOut } from "@/api"
import { tokenStorage } from "@/utils/token"

const actions = {
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone);
        // console.log(result);
        if (result.code == 200) {
            commit("GETCODE", result.data)
        }
    },

    async finishRegister({ commit }, user) {
        let result = await reqFinishRegister(user);
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new error('fail'))
        }
    },

    async userLogin({ commit }, user) {
        let result = await reqUserLogin(user);
        if (result.code == 200) {
            commit("USERLOGIN", result.data.token);
            tokenStorage(result.data.token);
            return 'ok'
        } else {
            return Promise.reject(new Error("fail"))
        }
    },

    async getUserInfo({ commit }) {
        let result = await reqUserInfo();
        if (result.code == 200) {
            commit("GETUSERINFO", result.data);
            return "ok"
        } else {
            return Promise.reject(new error("fail"))
        }
    },

    async loginOut({ commit }) {
        let result = await reqLoginOut();
        if (result.code == 200) {
            localStorage.removeItem("token");
            commit("CLEARUSER");
            return 'ok'
        } else {
            return Promise.reject(new error('fail'))
        }
    },
};

const mutations = {
    GETCODE(state, data) {
        state.code = data
    },

    USERLOGIN(state, data) {
        state.token = data
    },

    GETUSERINFO(state, data) {
        state.userInfo = data
    },

    CLEARUSER(state) {
        state.userInfo = {};
        state.token = ""
    }
};

const state = {
    code: '',
    token: localStorage.getItem("token"),
    userInfo: {}
};

export default {
    actions, mutations, state
}